NextJs / APIs / API with useState and useEffect
API , UseState and useEffect
-
API with UI
useState is used to define state variable to update the UI after rendering
'use client' import React from 'react'; import { useState, useEffect } from "react"; export default function Home() { const [posts, setPosts] = useState([]); const loadPost = async () => { const res = await fetch( "https://jsonplaceholder.typicode.com/posts/" ); const data = await res.json(); // After fetching data stored it in posts state. setPosts(data); }; // Call the function loadPost(); return ( { posts.map((item) => (); })) }{item.title}
Note that there will be infinitive API call To fix this side effect of API call, we need to use useEffect 'use client' import React from 'react'; import { useState, useEffect } from "react"; export default function Home() { const [posts, setPosts] = useState([]); useEffect(() => { const loadPost = async () => { const res = await fetch( "https://jsonplaceholder.typicode.com/posts/" ); const data = await res.json(); // After fetching data stored it in posts state. setPosts(data); }; // Call the function loadPost(); }, []); return ( { posts.map((item) => (); })) }{item.title}
MANVIA BLOG